package com.vrv.app.cyberspace.modules.sys.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.vrv.app.cyberspace.common.ddio.ApiV2Service;
import com.vrv.app.cyberspace.common.ddio.DDIORunnable;
import com.vrv.app.cyberspace.common.ddio.TemplateMessage;
import com.vrv.app.cyberspace.common.utils.HttpContextUtils;
import com.vrv.app.cyberspace.common.utils.JSONResult;
import com.vrv.app.cyberspace.config.WXBSystemConfig;
import com.vrv.app.cyberspace.modules.sys.entity.EventApprovalTable;
import com.vrv.app.cyberspace.modules.sys.entity.EventManageTable;
import com.vrv.app.cyberspace.modules.sys.entity.RoleTable;
import com.vrv.app.cyberspace.modules.sys.entity.UserTable;
import com.vrv.app.cyberspace.modules.sys.mapper.*;
import com.vrv.app.cyberspace.modules.sys.service.IEventApprovalTableService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.vrv.app.cyberspace.common.utils.JSONResult.renderError;
import static com.vrv.app.cyberspace.common.utils.JSONResult.renderSuccess;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sm
 * @since 2017-12-25
 */
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Service
@Transactional
public class EventApprovalTableServiceImpl extends ServiceImpl<EventApprovalTableMapper, EventApprovalTable> implements IEventApprovalTableService {
    Logger logger = LoggerFactory.getLogger(RiskTableServiceImpl.class);

    private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    @Autowired
    private EventManageTableMapper eventManageTableMapper;
    @Autowired
    private EventTypeTableMapper eventTypeTableMapper;
    @Autowired
    private RoleTableMapper roleTableMapper;
    @Autowired
    private UserTableMapper userTableMapper;
    @Autowired
    private ApiV2Service apiV2Service;
    @Autowired
    private WXBSystemConfig wxbSystemConfig;
    private ExecutorService executorService = Executors.newSingleThreadExecutor();

    //同意操作，事件状态为1等待审批的时候可进行此操作
    @Override
    public JSONResult endEventApproval(Integer id, String advice) {
        UserTable userTable = (UserTable) HttpContextUtils.getHttpServletRequest().getSession().getAttribute("user");
        RoleTable roleTable = roleTableMapper.selectById(userTable.getRoleID());
        if (roleTable.getRoleRank().equals("6")){
            return renderError("操作被禁止，专家只能进行退回操作！");
        }
        EventManageTable emt = eventManageTableMapper.selectById(id);
        if (emt.getStatus()==4){
            return renderError("操作被禁止，此事件已审批完成!");
        }
        if (!emt.getApprovalUserID().equals(userTable.getLinkdoodID())){
            return renderError("操作被禁止，当前用户非审批人！");
        }
        //新增审批流程状态7领导同意
        Date now = new Date();
        EventApprovalTable neweat1 = new EventApprovalTable();
        neweat1.setBaseID(id);
        neweat1.setUserID(userTable.getLinkdoodID());
        neweat1.setApprovalStatue(7);
        neweat1.setCreateTime(now);
        neweat1.setAdvice(advice);
        neweat1.insert();
/*        //新增审批流程状态 8.等待下发或归档
        EventApprovalTable neweat2 = new EventApprovalTable();
        neweat2.setBaseID(id);
        neweat2.setUserID(null);
        neweat2.setApprovalStatue(8);
        neweat2.setCreateTime(now);
        neweat1.setAdvice(null);
        neweat2.insert();*/
        //更改事件状态为审批通过，等待下发或者归档
        emt.setStatus(4);
        emt.setUpdateTime(now);
        emt.setApprovalUserID(emt.getCreateUserID());
        emt.updateById();
        logger.info("事件管理审批"+emt.getBaseID()+"由"+userTable.getLinkdoodID()+"-"+userTable.getLinkdoodName()+"审批同意");
        return renderSuccess();
    }

    //退回操作，事件状态为1等待审批的时候可进行此操作
    @Override
    public JSONResult backEventApproval(Integer id, String advice) {
        UserTable userTable = (UserTable) HttpContextUtils.getHttpServletRequest().getSession().getAttribute("user");
        RoleTable roleTable = roleTableMapper.selectById(userTable.getRoleID());
        EventManageTable emt = eventManageTableMapper.selectById(id);
        if (emt.getStatus()==4){
            return renderError("操作被禁止，此事件已审批完成!");
        }
        if (!emt.getApprovalUserID().equals(userTable.getLinkdoodID())){
            return renderError("操作被禁止，当前用户非审批人！");
        }
        //新增审批流程状态
        Date now = new Date();
        EventApprovalTable neweat1 = new EventApprovalTable();
        neweat1.setBaseID(id);
        neweat1.setUserID(userTable.getLinkdoodID());
        //如果操作人为专家状态则为4研判完毕，否则为3.领导退回
        if ("6".equals(roleTable.getRoleRank())){
            neweat1.setApprovalStatue(4);
        }else {
            neweat1.setApprovalStatue(3);
        }
        neweat1.setCreateTime(now);
        neweat1.setAdvice(advice);
        neweat1.insert();
/*        //新增审批流程状态5值班员审核中
        EventApprovalTable neweat2 = new EventApprovalTable();
        neweat2.setBaseID(id);
        neweat2.setUserID(null);
        neweat2.setApprovalStatue(5);
        neweat2.setCreateTime(now);
        neweat1.setAdvice(null);
        neweat2.insert();*/
        //更改事件状态为值班员审批，等待值班员重新请示领导
        emt.setStatus(1);
        emt.setUpdateTime(now);
        emt.setApprovalUserID(emt.getCreateUserID());
        emt.updateById();
        logger.info("事件管理审批"+emt.getBaseID()+"由"+userTable.getLinkdoodID()+"-"+userTable.getLinkdoodName()+"审批退回");
        pushTemplateMessage(emt, emt.getCreateUserID(),eventTypeTableMapper.selectById(emt.getPrimaryEventTypeFirst()).getName(),eventTypeTableMapper.selectById(emt.getPrimaryEventTypeSecond()).getName());
        return renderSuccess();
    }

    // 转批操作，事件状态为1等待审批的时候可进行此操作
    @Override
    public JSONResult addEventApproval(Integer id, String advice, String approvalUserID) {
        UserTable userTable = (UserTable) HttpContextUtils.getHttpServletRequest().getSession().getAttribute("user");
        RoleTable roleTable = roleTableMapper.selectById(userTable.getRoleID());
        UserTable approvalUser = userTableMapper.selectById(approvalUserID);
        RoleTable approvalUserRole = roleTableMapper.selectById(approvalUser.getRoleID());
        if (!roleTable.getRoleRank().equals("2")){
            if (approvalUserRole.getRoleRank().equals("6")){
                return renderError("操作被禁止，只有值班员才能进行研判！");
            }
        }
        if (roleTable.getRoleRank().equals("6")){
            return renderError("操作被禁止，专家只能进行退回操作！");
        }
        EventManageTable emt = eventManageTableMapper.selectById(id);
        if (emt.getStatus()==4){
            return renderError("操作被禁止，此事件已审批完成!");
        }
        if (!emt.getApprovalUserID().equals(userTable.getLinkdoodID())){
            return renderError("操作被禁止，当前用户非审批人！");
        }
        //新增审批流程状态，为6请示上级领导中
        Date now = new Date();
        EventApprovalTable neweat1 = new EventApprovalTable();
        neweat1.setBaseID(id);
        neweat1.setUserID(userTable.getLinkdoodID());
        if (approvalUserRole.getRoleRank().equals("6")) {
            neweat1.setApprovalStatue(2);
        }else {
            neweat1.setApprovalStatue(6);
        }
        neweat1.setCreateTime(now);
        neweat1.setAdvice(advice);
        neweat1.insert();
/*        //新增审批流程状态，如果请示人为专家状态则为2专家研判中，否则为1领导审批中
        EventApprovalTable neweat2 = new EventApprovalTable();
        neweat2.setBaseID(id);
        neweat2.setUserID(null);
        if (approvalUserRole.getRoleRank().equals("6")) {
            neweat2.setApprovalStatue(2);
        } else {
            neweat2.setApprovalStatue(1);
        }
        neweat2.setCreateTime(now);
        neweat2.setAdvice(null);
        neweat2.insert();*/
        //更改事件状态为领导审批，等待领导审批
        emt.setStatus(2);
        emt.setUpdateTime(now);
        emt.setApprovalUserID(approvalUserID);
        emt.updateById();
        logger.info("事件管理审批"+emt.getBaseID()+"由"+userTable.getLinkdoodID()+"-"+userTable.getLinkdoodName()+"转批，转批人为："+ approvalUserID);
        pushTemplateMessage(emt, approvalUserID,eventTypeTableMapper.selectById(emt.getPrimaryEventTypeFirst()).getName(),eventTypeTableMapper.selectById(emt.getPrimaryEventTypeSecond()).getName());
        return renderSuccess();
    }

    // 归档操作，事件状态如果等于2审批完成或者4下发完成的时候可进行此操作
    @Override
    public JSONResult archiveEventApproval(Integer id, String advice) {
        UserTable userTable = (UserTable) HttpContextUtils.getHttpServletRequest().getSession().getAttribute("user");
        RoleTable roleTable = roleTableMapper.selectById(userTable.getRoleID());
        EventManageTable emt = eventManageTableMapper.selectById(id);
        if (emt.getStatus()==7){
            return renderError("操作被禁止，此事件已归档!");
        }
        if (!roleTable.getRoleType().equals("ROLE_DUTY")){
            return renderError("操作被禁止，非值班员无法归档！");
        }
        //新增审批流程状态13归档完毕
        Date now = new Date();
        EventApprovalTable neweat = new EventApprovalTable();
        neweat.setBaseID(id);
        neweat.setUserID(userTable.getLinkdoodID());
        neweat.setApprovalStatue(13);
        neweat.setCreateTime(now);
        neweat.setAdvice(null);
        neweat.insert();
        //更改事件状态为已归档
        emt.setStatus(7);
        emt.setSummary(advice);
        emt.setUpdateTime(now);
        emt.updateById();
        logger.info("事件管理审批"+emt.getBaseID()+"由"+userTable.getLinkdoodID()+"-"+userTable.getLinkdoodName()+"归档");
        return renderSuccess();
    }

    // 下发操作，事件状态如果等于2审批完成的时候可进行此操作
    @Override
    public JSONResult releaseEventApproval(Integer id, String advice) {
        UserTable userTable = (UserTable) HttpContextUtils.getHttpServletRequest().getSession().getAttribute("user");
        EventManageTable emt = eventManageTableMapper.selectById(id);
        if (emt.getStatus()==5){
            return renderError("操作被禁止，此事件已进行下发操作!");
        }
        if (!emt.getApprovalUserID().equals(userTable.getLinkdoodID())){
            return renderError("操作被禁止，当前用户非审批人！");
        }
        //新增审批流程状态9已下发
        Date now = new Date();
/*        EventApprovalTable neweat1 = new EventApprovalTable();
        neweat1.setBaseID(id);
        neweat1.setUserID(userTable.getLinkdoodID());
        neweat1.setApprovalStatue(9);
        neweat1.setCreateTime(now);
        neweat1.setAdvice(advice);
        neweat1.insert();*/
/*        //新增审批流程状态10反馈中
        EventApprovalTable neweat2 = new EventApprovalTable();
        neweat2.setBaseID(id);
        neweat2.setUserID(null);
        neweat2.setApprovalStatue(10);
        neweat2.setCreateTime(now);
        neweat2.setAdvice(null);
        neweat2.insert();*/
        //更改事件状态为下发中
        emt.setStatus(5);
        emt.setUpdateTime(now);
        emt.setApprovalUserID(emt.getCreateUserID());
        emt.updateById();
        logger.info("事件管理审批"+emt.getBaseID()+"由"+userTable.getLinkdoodID()+"-"+userTable.getLinkdoodName()+"下发");
        pushTemplateMessage(emt, emt.getCreateUserID(),eventTypeTableMapper.selectById(emt.getPrimaryEventTypeFirst()).getName(),eventTypeTableMapper.selectById(emt.getPrimaryEventTypeSecond()).getName());
        return renderSuccess();
    }

    // 反馈操作，事件状态如果等于3下发中的时候可进行此操作
    @Override
    public JSONResult feedbackEventApproval(Integer id, String advice) {
        UserTable userTable = (UserTable) HttpContextUtils.getHttpServletRequest().getSession().getAttribute("user");
        EventManageTable emt = eventManageTableMapper.selectById(id);
        if (emt.getStatus()==6){
            return renderError("操作被禁止，此事件已反馈完毕!");
        }
        if (!emt.getApprovalUserID().equals(userTable.getLinkdoodID())){
            return renderError("操作被禁止，当前用户非审批人！");
        }
        //更改旧审批流程状态11反馈完毕
        Date now = new Date();
/*        EventApprovalTable neweat1 = new EventApprovalTable();
        neweat1.setBaseID(id);
        neweat1.setUserID(userTable.getLinkdoodID());
        neweat1.setApprovalStatue(11);
        neweat1.setCreateTime(now);
        neweat1.setAdvice(advice);
        neweat1.insert();*/
/*        //新增审批流程状态12等待归档中
        EventApprovalTable neweat2 = new EventApprovalTable();
        neweat2.setBaseID(id);
        neweat2.setUserID(null);
        neweat2.setApprovalStatue(12);
        neweat2.setCreateTime(now);
        neweat2.setAdvice(null);
        neweat2.insert();*/
        //更改事件状态为下发完成（反馈完毕）
        emt.setStatus(6);
        emt.setUpdateTime(now);
        emt.setApprovalUserID(emt.getCreateUserID());
        emt.updateById();
        logger.info("事件管理审批"+emt.getBaseID()+"由"+userTable.getLinkdoodID()+"-"+userTable.getLinkdoodName()+"反馈完毕");
        pushTemplateMessage(emt, emt.getCreateUserID(),eventTypeTableMapper.selectById(emt.getPrimaryEventTypeFirst()).getName(),eventTypeTableMapper.selectById(emt.getPrimaryEventTypeSecond()).getName());
        return renderSuccess();
    }

    private void pushTemplateMessage(EventManageTable emt, String toUsers,String typeFirst,String typeSecond) {
        String appid = apiV2Service.getAppID();
        String content = "时间: " + dateFormat.format(new Date()) + "\n标题：" + emt.getTitle() + "\n类别: " + typeFirst+"-"+typeSecond + "\n请您及时处理 ";
        TemplateMessage templateMessage = TemplateMessage.createOne(appid,"事件管理", appid, content, wxbSystemConfig.getEventFeedbackDetailUrl() + "&id=" + emt.getBaseID(),
                toUsers);
        try {
            executorService.execute(new DDIORunnable(apiV2Service, "sendTemplateMsg", templateMessage, TemplateMessage.class));
        } catch (NoSuchMethodException e) {
            logger.info("推送事件管理"+"(ID" + emt.getBaseID() + ")消息失败! ");
            e.printStackTrace();
        }
    }
}
